//
//  IDOLaunchAdButton.m
//  IDOLaunchAd
//
//  Created by 卓勇  on 2017/6/7.
//  Copyright © 2017年 zhuoyong. All rights reserved.
//

#import "IDOLaunchAdButton.h"

@interface IDOLaunchAdButton ()

@property (nonatomic, assign) IDOLaunchAdButtonType launchAdButtonType ; // 按钮类型

@end

@implementation IDOLaunchAdButton

static CGFloat radiusFromAngle(CGFloat angle) {
    return (angle * M_PI) / 180.0;
}

- (instancetype)initWithFrame:(CGRect)frame LaunchAdButtonType:(IDOLaunchAdButtonType)type {
    self = [super initWithFrame:frame];
    
    if (self) {
        self.launchAdButtonType = type;
        [self commonInit];
    }
    
    return self;
}

- (void)commonInit {
    switch (_launchAdButtonType) {
        case Circle: {
            // 圆形进度按钮
            self.circleLineWidth = 3;
            self.circleProgress = 0;
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - draw rect
- (void)drawRect:(CGRect)rect {
    
    switch (_launchAdButtonType) {
        case Circle: {
            // 圆形进度按钮
            CGContextRef context = UIGraphicsGetCurrentContext();
            
            CGFloat centerX = self.bounds.size.width / 2.0;
            CGFloat centerY = self.bounds.size.height / 2.0;
            CGFloat radius = (self.bounds.size.width - self.circleLineWidth) / 2.0;
            
            // 背景圆形（填充色黑色，画笔色红色）
            UIColor*fillColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
            CGContextSetFillColorWithColor(context, fillColor.CGColor);// 填充颜色
            CGContextSetLineWidth(context, self.circleLineWidth);// 线的宽度
            CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); // 画笔颜色
            CGContextAddArc(context, centerX, centerY, radius, 0, 2 * M_PI, 0); // 添加一个圆
            CGContextDrawPath(context, kCGPathFillStroke); // 绘制路径加填充
            
            // 进度条轨道
            CGFloat endAngle = _circleProgress * 2 * M_PI;
            CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0); // 画笔颜色
            CGContextSetLineWidth(context, self.circleLineWidth);// 线的宽度
            CGContextAddArc(context, centerX, centerY, radius, radiusFromAngle(-90), endAngle + radiusFromAngle(-90), 0); // 添加一个圆
            CGContextDrawPath(context, kCGPathStroke); // 绘制路径
        }
            break;
            
        default:
            break;
    }
}

- (void)stateWithLaunchAdButtonType:(IDOLaunchAdButtonType)type andDuration:(CGFloat)duration {
    switch (type) {
        case Circle: {
            self.circleProgress += duration;
            [self setNeedsDisplay];
        }
            break;
            
        default: {
            [self setTitle:[NSString stringWithFormat:@"%lds 跳过", (long)duration] forState:UIControlStateNormal];
        }
            break;
    }
}

@end
